/**
 * 
 */
package com.efast.cafe.portal.service.company.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.efast.cafe.commponent.query.service.impl.QueryServiceImpl;
import com.efast.cafe.framework.bean.QueryPageBase;
import com.efast.cafe.framework.util.QueryStringUtil;
import com.efast.cafe.portal.bean.query.AbstractFieldType;
import com.efast.cafe.portal.bean.query.QueryBean;
import com.efast.cafe.portal.bean.query.QueryConditionBean;
import com.efast.cafe.util.SetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import com.efast.cafe.framework.constant.CommonConstant;
import com.efast.cafe.framework.constant.SecurityConstant;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.jdbc.JdbcDaoImpl;
import com.efast.cafe.framework.jdbc.persistence.Criteria;
import com.efast.cafe.framework.pager.Pagination;
import com.efast.cafe.framework.redis.ObjectRedisTemplate;
import com.efast.cafe.framework.service.CafeServiceImpl;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.bean.company.PortalCompanyUserAddEditBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserOrgBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserOrgPositionBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserOrgsBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserQueryBean;
import com.efast.cafe.portal.dao.company.PortalCompanyOrgDao;
import com.efast.cafe.portal.dao.company.PortalCompanyUserDao;
import com.efast.cafe.portal.dao.company.PortalCompanyUserReporttoDao;
import com.efast.cafe.portal.entity.company.PortalCompanyOrg;
import com.efast.cafe.portal.entity.company.PortalCompanyPosition;
import com.efast.cafe.portal.entity.company.PortalCompanyRole;
import com.efast.cafe.portal.entity.company.PortalCompanyUser;
import com.efast.cafe.portal.entity.company.PortalCompanyUserLevel;
import com.efast.cafe.portal.entity.company.PortalCompanyUserOrg;
import com.efast.cafe.portal.entity.company.PortalCompanyUserOrgListDto;
import com.efast.cafe.portal.entity.company.PortalCompanyUserReporttoTreeDto;
import com.efast.cafe.portal.entity.company.PortalCompanyUserRole;
import com.efast.cafe.portal.service.company.IPortalCompanyUserService;
import com.efast.cafe.util.StringUtil;
import com.github.pagehelper.PageHelper;

/**
 * 企业用户管理-Service实现层
 * 
 * @author xl
 * 
 */
@Service
@Transactional
@RestController
public class PortalCompanyUserServiceImpl extends CafeServiceImpl<PortalCompanyUser> implements IPortalCompanyUserService {

	@Qualifier("jdbcDao")
	@Autowired
	private JdbcDao jdbcDao;

	private PortalCompanyUserDao portalCompanyUserDao;

	private ObjectRedisTemplate objectRedisTemplate;

	private PortalCompanyOrgDao portalCompanyOrgDao;
	
	@Autowired
	private PortalCompanyUserReporttoDao portalCompanyUserReporttoDao;

	@Autowired
	public void setObjectRedisTemplate(ObjectRedisTemplate objectRedisTemplate) {
		this.objectRedisTemplate = objectRedisTemplate;
	}

	@Autowired
	public void setPortalCompanyOrgDao(PortalCompanyOrgDao portalCompanyOrgDao) {
		this.portalCompanyOrgDao = portalCompanyOrgDao;
	}

	@Autowired
	public void setPortalCompanyUserDao(PortalCompanyUserDao portalCompanyUserDao) {
		this.portalCompanyUserDao = portalCompanyUserDao;
	}

	
	
	
	@Override
	public List<PortalCompanyUserReporttoTreeDto> getAdvancedSearch(PortalCompanyUserReporttoTreeDto portalCompanyUserReporttoTreeDto) {

		List<PortalCompanyUserReporttoTreeDto> list = new ArrayList<PortalCompanyUserReporttoTreeDto>();

		Criteria userCriteria = Criteria.create(PortalCompanyUser.class).where("companyCode",
				new Object[] { SpringWebUtils.getRequestCompany() });
		List<PortalCompanyUser> listUser = jdbcDao.queryList(userCriteria);

		Map<String, PortalCompanyUser> mapUser = new HashMap<String, PortalCompanyUser>();
		for (PortalCompanyUser portalCompanyUser : listUser) {
			mapUser.put(portalCompanyUser.getUsername(), portalCompanyUser);
		}

		List<String> partsList = new ArrayList<String>();
		if (portalCompanyUserReporttoTreeDto.getType() != null && !"".equals(portalCompanyUserReporttoTreeDto.getType())) {
			String[] parts = portalCompanyUserReporttoTreeDto.getType().split(",");
			partsList = Arrays.asList(parts);
		}
		if(partsList.isEmpty()){
			partsList.add("all");
		}
		Map<Long, String> map = new HashMap<>() ;
		if (partsList.contains("all") || partsList.contains("organization")) {
			Criteria orgCriteria = Criteria.create(PortalCompanyOrg.class).where(PortalCompanyOrg.companyCode,
					new Object[] { SpringWebUtils.getRequestCompany() });
			List<PortalCompanyOrg> listOrg = jdbcDao.queryList(orgCriteria);
			for (PortalCompanyOrg portalCompanyOrg : listOrg) {
				map.put(portalCompanyOrg.getPortal_company_org_id(), portalCompanyOrg.getOrg_name());
			}
			
			for (PortalCompanyOrg portalCompanyOrg : listOrg) {
				PortalCompanyUserReporttoTreeDto dto = new PortalCompanyUserReporttoTreeDto();
				dto.setId("org_" + portalCompanyOrg.getPortal_company_org_id());
				dto.setName(portalCompanyOrg.getOrg_name());
				dto.setParentId("org_" + portalCompanyOrg.getParent_id());
				
				dto.setParentName(map.get(portalCompanyOrg.getParent_id()));
				dto.setType("org");
				dto.setIconSkin("org");
				dto.setIsHidden(false);
				
				if(portalCompanyUserReporttoTreeDto.getKeyWords()!=null && StringUtil.isNotBlank(dto.getName())){
					if(dto.getName().indexOf(portalCompanyUserReporttoTreeDto.getKeyWords())!=-1){
						list.add(dto);
					}
				}else{
					list.add(dto);
				}
			}

		}
		Map<Long, String> mapPosition = new HashMap<>() ;
		if (partsList.contains("all") || partsList.contains("position")) {
			Criteria positionCriteria = Criteria.create(PortalCompanyPosition.class).where(PortalCompanyOrg.companyCode,
					new Object[] { SpringWebUtils.getRequestCompany() });
			List<PortalCompanyPosition> listPosition = jdbcDao.queryList(positionCriteria);
			for (PortalCompanyPosition portalCompanyPosition : listPosition) {
				mapPosition.put(portalCompanyPosition.getPortal_company_position_id(), portalCompanyPosition.getPosition_name());
			}
			for (PortalCompanyPosition portalCompanyPosition : listPosition) {
				PortalCompanyUserReporttoTreeDto dto = new PortalCompanyUserReporttoTreeDto();
				dto.setId("position_" + portalCompanyPosition.getPortal_company_position_id());
				dto.setName(portalCompanyPosition.getPosition_name());
				dto.setParentId("org_" + portalCompanyPosition.getPortal_company_org_id());
				dto.setParentName(map.get(portalCompanyPosition.getPortal_company_org_id()));
				dto.setType("position");
				dto.setIsHidden(false);
				dto.setIconSkin("position");
				if(portalCompanyUserReporttoTreeDto.getKeyWords()!=null && StringUtil.isNotBlank(dto.getName())){
					if(dto.getName().indexOf(portalCompanyUserReporttoTreeDto.getKeyWords())!=-1){
						list.add(dto);
					}
				}else{
					list.add(dto);
				}
			}

		}
		
		if (partsList.contains("all") || partsList.contains("person")) {
			
			List<PortalCompanyUserOrg> listUserOrg = portalCompanyUserReporttoDao.queryUserOrgList();
			for (PortalCompanyUserOrg portalCompanyUserOrg : listUserOrg) {
				PortalCompanyUserReporttoTreeDto user = new PortalCompanyUserReporttoTreeDto();
				user.setId("user_" + portalCompanyUserOrg.getUsername() + "_"
						+ portalCompanyUserOrg.getPortal_company_user_org_id());
				user.setName(portalCompanyUserOrg.getUsername());
				user.setParentId("position_" + portalCompanyUserOrg.getPortal_company_position_id());
				user.setParentName(mapPosition.get(portalCompanyUserOrg.getPortal_company_position_id()));
				user.setType("user");
				user.setIsHidden(false);
				user.setIconSkin("user");
				if(portalCompanyUserReporttoTreeDto.getKeyWords()!=null && StringUtil.isNotBlank(user.getName())){
					if(user.getName().indexOf(portalCompanyUserReporttoTreeDto.getKeyWords())!=-1){
						list.add(user);
					}
				}else{
					list.add(user);
				}
			}

		}

		if (partsList.contains("all") || partsList.contains("level")) {
			Criteria levelCriteria = Criteria.create(PortalCompanyUserLevel.class)
					.where(PortalCompanyUserLevel.COMPANY_CODE, new Object[] { SpringWebUtils.getRequestCompany() });
			List<PortalCompanyUserLevel> levelPosition = jdbcDao.queryList(levelCriteria);
			for (PortalCompanyUserLevel portalCompanyUserLevel : levelPosition) {
				PortalCompanyUserReporttoTreeDto dto = new PortalCompanyUserReporttoTreeDto();
				dto.setId("level_" + portalCompanyUserLevel.getPortal_company_user_level_id());
				dto.setName(portalCompanyUserLevel.getLevel_name());
				dto.setParentId("");
				dto.setType("level");
				dto.setIsHidden(false);
				dto.setIconSkin("level");
				if(portalCompanyUserReporttoTreeDto.getKeyWords()!=null
						&& StringUtil.isNotBlank(dto.getName())
						&&dto.getName().indexOf(portalCompanyUserReporttoTreeDto.getKeyWords())!=-1){
					list.add(dto);
				}else{
					list.add(dto);
				}
			}

		}

		return list;
	}
	
	
	
	
	@Override
	public List<PortalCompanyUserReporttoTreeDto> getUserListByCondition(PortalCompanyUserReporttoTreeDto thisDto) {
		
		List<PortalCompanyUserReporttoTreeDto> list=new ArrayList<PortalCompanyUserReporttoTreeDto>();
		
		Criteria  userCriteria=Criteria.create(PortalCompanyUser.class).where("companyCode", new Object[]{SpringWebUtils.getRequestCompany()});
		List<PortalCompanyUser> listUser= jdbcDao.queryList(userCriteria);
		
		Map<String, PortalCompanyUser> mapUser=new HashMap<String, PortalCompanyUser>();
		for (PortalCompanyUser portalCompanyUser : listUser) {
			mapUser.put(portalCompanyUser.getUsername(), portalCompanyUser);
		}
		Map<Long, String> map = new HashMap<>() ;
		Criteria orgCriteria=Criteria.create(PortalCompanyOrg.class).where(PortalCompanyOrg.companyCode, new Object[]{SpringWebUtils.getRequestCompany()});
		List<PortalCompanyOrg> listOrg= jdbcDao.queryList(orgCriteria);
		for (PortalCompanyOrg portalCompanyOrg : listOrg) {
			map.put(portalCompanyOrg.getPortal_company_org_id(), portalCompanyOrg.getOrg_name());
		}
		
		for (PortalCompanyOrg portalCompanyOrg : listOrg) {
			PortalCompanyUserReporttoTreeDto dto = new PortalCompanyUserReporttoTreeDto();
			dto.setId("org_"+portalCompanyOrg.getPortal_company_org_id());
			dto.setName(portalCompanyOrg.getOrg_name());
			dto.setParentId("org_"+portalCompanyOrg.getParent_id());
			dto.setParentName(map.get(portalCompanyOrg.getParent_id()));
			dto.setType("org");
			dto.setIconSkin("org");
			dto.setIsHidden(false);
			list.add(dto);
		}
		Map<Long, String> mapPosition = new HashMap<>() ;
		 Criteria positionCriteria=Criteria.create(PortalCompanyPosition.class).where(PortalCompanyOrg.companyCode, new Object[]{SpringWebUtils.getRequestCompany()});
		 List<PortalCompanyPosition> listPosition=jdbcDao.queryList(positionCriteria);
		 for (PortalCompanyPosition portalCompanyPosition : listPosition) {
				mapPosition.put(portalCompanyPosition.getPortal_company_position_id(), portalCompanyPosition.getPosition_name());
			}
		 for (PortalCompanyPosition portalCompanyPosition : listPosition) {
			 PortalCompanyUserReporttoTreeDto dto = new PortalCompanyUserReporttoTreeDto();
			 dto.setId("position_"+portalCompanyPosition.getPortal_company_position_id());
			 dto.setName(portalCompanyPosition.getPosition_name());
			 dto.setParentId("org_"+portalCompanyPosition.getPortal_company_org_id());
			 dto.setParentName(map.get(portalCompanyPosition.getPortal_company_org_id()));
			 dto.setType("position");
			 dto.setIsHidden(false);
			 dto.setIconSkin("position");
			 list.add(dto); 
		 }
	 
		 List<PortalCompanyUserOrgListDto> listUserOrg=portalCompanyUserReporttoDao.queryUserListByCondition(
				 thisDto.getUsername(), SpringWebUtils.getRequestCompany(), thisDto.getPhone(), thisDto.getEmail());
		 for (PortalCompanyUserOrgListDto portalCompanyUserOrgListDto : listUserOrg) {
			 PortalCompanyUserReporttoTreeDto user = new PortalCompanyUserReporttoTreeDto();
			 user.setId("user_"+portalCompanyUserOrgListDto.getUsername()+"_"+mapUser.get(portalCompanyUserOrgListDto.getUsername()).getPortal_company_user_id());
			 user.setName(portalCompanyUserOrgListDto.getUsername());
			 user.setParentId("position_"+portalCompanyUserOrgListDto.getPortal_company_position_id());
			 user.setParentName(mapPosition.get(portalCompanyUserOrgListDto.getPortal_company_position_id()));
			 user.setType("user");
			 user.setIsHidden(false);
			 user.setIconSkin("user");
			 
			 user.setUserId(portalCompanyUserOrgListDto.getPortal_company_user_id());
			 
			 list.add(user);
		 }
		 
		 List<PortalCompanyUserReporttoTreeDto> listR=new ArrayList<PortalCompanyUserReporttoTreeDto>();
		 
		 if("company".equals(thisDto.getType())){
			 listR = list;
		 }else if("organization".equals(thisDto.getType())){
			 List<String> ids = new ArrayList<String>();
			 for(PortalCompanyUserReporttoTreeDto dto : list){
				 if(("org_"+thisDto.getId()).equals(dto.getParentId())){
					 listR.add(dto);
					 ids.add(dto.getId());
				 }
			 }
			 while(ids.size()>0){
				 List<String> thisId = new ArrayList<String>();
				 for(String i : ids){
					 thisId.add(i);
				 }
				 ids.clear();
				 for(PortalCompanyUserReporttoTreeDto dto : list){
					 if(thisId.contains(dto.getParentId())){
						 listR.add(dto);
						 ids.add(dto.getId());
					 }
				 }				 
			 }
		 }else if("position".equals(thisDto.getType())){
			 for(PortalCompanyUserReporttoTreeDto dto : list){
				 if(("position_"+thisDto.getId()).equals(dto.getParentId())){
					 listR.add(dto);
				 }
			 }
		 }
		 
		 List<PortalCompanyUserReporttoTreeDto> listReturn=new ArrayList<PortalCompanyUserReporttoTreeDto>();
		 if(thisDto.getLevel()==null||"".equals(thisDto.getLevel())){
			 listReturn=listR;
		 }else{
			 for(PortalCompanyUserReporttoTreeDto dto : listR){
				 if(thisDto.getLevel().equals(dto.getType())){
					 listReturn.add(dto); 
				 }
			 }
		 }
		 
		return listReturn;
	}
	
	
	
	
	
	

	/**
	 * 分页查询企业用户列表 默认附加条件companyCode
	 * 
	 * @param pager
	 * @param username
	 *            根据用户名模糊匹配
	 * @return
	 */
	@Override
	public Pagination<PortalCompanyUser> queryPageUserList(Pagination<PortalCompanyUser> pager, String username,
			String email, String phone) {
		/*
		 * return portalCompanyUserDao.queryPageUserList(pager, username,
		 * SpringWebUtils.getRequestCompany(),email,phone);
		 */
		PortalCompanyUserBean userInfo = portalCompanyUserDao.queryUserInfo(SpringWebUtils.getRequestCompany(),
				SpringWebUtils.getRequestUser());
		Criteria criteria = Criteria.create(PortalCompanyUser.class).where(PortalCompanyUser.isDelete,
				new Object[] { 0 });
		criteria.and(PortalCompanyUser.Type, new Object[] { 1 });
		if (userInfo.getCompanyType() != 1) {
			criteria.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() });
		}

		if (!StringUtil.isEmpty(username)) {
			criteria.and(PortalCompanyUser.Username, Criteria.FIELD_OPERATOR_LIKE,
					new Object[] { "%" + username + "%" });
		}
		if (!StringUtil.isEmpty(email)) {
			criteria.and(PortalCompanyUser.Email, Criteria.FIELD_OPERATOR_LIKE, new Object[] { "%" + email + "%" });
		}
		if (!StringUtil.isEmpty(phone)) {
			criteria.and(PortalCompanyUser.Phone, Criteria.FIELD_OPERATOR_LIKE, new Object[] { "%" + phone + "%" });
		}
		return jdbcDao.queryListByPage(pager, criteria);
	}

	/**
	 * 根据id获取企业用户 默认附加条件companyCode
	 * 
	 * @param portalCompanyUserId
	 * @return
	 */
	@Override
	public PortalCompanyUser getCompanyUserById(Long portalCompanyUserId) {
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.where(PortalCompanyUser.portalCompanyUserId, new Object[] { portalCompanyUserId })
				.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() });
		List<PortalCompanyUser> list = jdbcDao.queryList(criteria);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			throw new ServiceException("该数据不存在");
		}

	}

	/**
	 * 新增企业用户 校验用户名是否存在 存在抛出ServiceException
	 * 
	 * @param portalCompanyUser
	 * @return
	 */
	@Override
	public Long insertCompanyUser(PortalCompanyUserAddEditBean portalCompanyUser, String pwd) throws ServiceException {
		if(StringUtil.isNullOrBlank(portalCompanyUser.getCompany_code())){
			portalCompanyUser.setCompany_code(SpringWebUtils.getRequestCompany());
		}
		boolean usernameIsExist = usernameIsExist(portalCompanyUser.getUsername(), portalCompanyUser.getCompany_code());
		if (usernameIsExist) {
			throw new ServiceException("用户名存在");
		} else {
			if (StringUtil.isEmpty(portalCompanyUser.getType())) {
				portalCompanyUser.setType("1");
			}
			BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			Long portalCompanyUserId = jdbcDao.insert(Criteria.create(PortalCompanyUser.class)
					.set(PortalCompanyUser.companyCode, portalCompanyUser.getCompany_code())
					.set(PortalCompanyUser.State, 1).set(PortalCompanyUser.Email, portalCompanyUser.getEmail())
					.set(PortalCompanyUser.Phone, portalCompanyUser.getPhone())
					.set(PortalCompanyUser.Username, portalCompanyUser.getUsername()).set(PortalCompanyUser.isDelete, 0)
					.set(PortalCompanyUser.createUser, SpringWebUtils.getRequestUser())
					.set(PortalCompanyUser.createTime, new Date()).set(PortalCompanyUser.lastUpdateTime, new Date())
					.set(PortalCompanyUser.realName, portalCompanyUser.getReal_name())
					.set(PortalCompanyUser.Sex, portalCompanyUser.getSex())
					.set(PortalCompanyUser.userLevel, portalCompanyUser.getUser_level())
					.set(PortalCompanyUser.Type, portalCompanyUser.getType())
					.set(PortalCompanyUser.Pwd, passwordEncoder.encode(pwd))
					.set(PortalCompanyUser.lastUpdateUser, SpringWebUtils.getRequestUser()));
			
			if(portalCompanyUser.getOrgPositionBeanList()!=null){
				for(PortalCompanyUserOrgPositionBean op : portalCompanyUser.getOrgPositionBeanList()){
					Criteria criteria = Criteria.create(PortalCompanyUserOrg.class).set(PortalCompanyUserOrg.companyCode, portalCompanyUser.getCompany_code())
							.set(PortalCompanyUserOrg.userName, portalCompanyUser.getUsername())
							.set(PortalCompanyUserOrg.portalCompanyOrgId, op.getOrgId())
							.set(PortalCompanyUserOrg.createUser, SpringWebUtils.getRequestUser())
							.set(PortalCompanyUserOrg.isDefault, op.getIsDefault());
					if(op.getPositionId() != null ){
						criteria.set(PortalCompanyUserOrg.portalCompanyPositionId, op.getPositionId());
					}
					jdbcDao.insert(criteria);
				}
			}
			
			return portalCompanyUserId;
		}
	}

	/**
	 * 修改企业用户
	 * 
	 * @param portalCompanyUser
	 */
	@Override
	public void updateCompanyUser(PortalCompanyUserAddEditBean portalCompanyUser) throws ServiceException {
		if(StringUtil.isNullOrBlank(portalCompanyUser.getCompany_code())){
			portalCompanyUser.setCompany_code(SpringWebUtils.getRequestCompany());
		}
		PortalCompanyUserBean user = portalCompanyUserDao.queryUserInfo(portalCompanyUser.getCompany_code(),
				SpringWebUtils.getRequestUser());
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.set(PortalCompanyUser.Email, portalCompanyUser.getEmail())
				.set(PortalCompanyUser.Phone, portalCompanyUser.getPhone())
				.set(PortalCompanyUser.lastUpdateUser, SpringWebUtils.getRequestUser())
				.set(PortalCompanyUser.realName, portalCompanyUser.getReal_name())
				.set(PortalCompanyUser.Sex, portalCompanyUser.getSex())
				.set(PortalCompanyUser.companyCode, portalCompanyUser.getCompany_code())
				.set(PortalCompanyUser.userLevel, portalCompanyUser.getUser_level())
				.where(PortalCompanyUser.portalCompanyUserId,
						new Object[] { portalCompanyUser.getPortal_company_user_id() })
				.and(PortalCompanyUser.Username, new Object[] { portalCompanyUser.getUsername() });
		if (user.getCompanyType() != 1) {
			criteria.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() });
		}
		jdbcDao.update(criteria);
		
		jdbcDao.delete(Criteria.create(PortalCompanyUserOrg.class).
				where(PortalCompanyUserOrg.companyCode, new Object[]{portalCompanyUser.getCompany_code()})
				.and(PortalCompanyUserOrg.userName, new Object[]{portalCompanyUser.getUsername()}));
		if(portalCompanyUser.getOrgPositionBeanList()!=null){
			for(PortalCompanyUserOrgPositionBean op : portalCompanyUser.getOrgPositionBeanList()){
				criteria = Criteria.create(PortalCompanyUserOrg.class).set(PortalCompanyUserOrg.companyCode, portalCompanyUser.getCompany_code())
						.set(PortalCompanyUserOrg.userName, portalCompanyUser.getUsername())
						.set(PortalCompanyUserOrg.portalCompanyOrgId, op.getOrgId())
						.set(PortalCompanyUserOrg.createUser, SpringWebUtils.getRequestUser())
						.set(PortalCompanyUserOrg.isDefault, op.getIsDefault());
				if(op.getPositionId() != null ){
					criteria.set(PortalCompanyUserOrg.portalCompanyPositionId, op.getPositionId());
				}
				jdbcDao.insert(criteria);
			}
		}

	}
	
	@Override
	public PortalCompanyUserAddEditBean queryEditDetailUser(PortalCompanyUserAddEditBean portalCompanyUser) {
		PortalCompanyUserOrgBean bean = portalCompanyUserDao.queryUserAndOrgInfo(SpringWebUtils.getRequestCompany(), portalCompanyUser.getUsername());
		portalCompanyUser.setCompany_code(bean.getCompanyCode());
		portalCompanyUser.setEmail(bean.getEmail());
		portalCompanyUser.setPhone(bean.getPhone());
		portalCompanyUser.setPortal_company_user_id(bean.getUserId());
		portalCompanyUser.setReal_name(bean.getRealName());
		portalCompanyUser.setSex(bean.getSex());
		portalCompanyUser.setType(bean.getType());
		portalCompanyUser.setUser_level(bean.getUserLevel());
		portalCompanyUser.setUsername(bean.getUsername());
		List<PortalCompanyUserOrgPositionBean> orgPositionBeanList = new ArrayList<PortalCompanyUserOrgPositionBean>();
		for(PortalCompanyUserOrgsBean uo : bean.getOrgs()){
			PortalCompanyUserOrgPositionBean b = new PortalCompanyUserOrgPositionBean();
			b.setIsDefault(uo.getIsDefault());
			b.setOrgId(uo.getOrgId());
			b.setOrgName(uo.getOrgName());
			b.setPositionId(uo.getPositionId());
			b.setPositionName(uo.getPositionName());
			orgPositionBeanList.add(b);
		}
		portalCompanyUser.setOrgPositionBeanList(orgPositionBeanList);
		return portalCompanyUser;
	}
	

	/**
	 * 校验用户名是否存在 默认附加条件companyCode
	 * 
	 * @param username
	 * @return
	 */
	@Override
	public boolean usernameIsExist(String username, String companyCode) {
		int count = jdbcDao.queryCount(Criteria.create(PortalCompanyUser.class)
				.where(PortalCompanyUser.companyCode, new Object[] { companyCode })
				.and(PortalCompanyUser.isDelete, new Object[] { 0 })
				.and(PortalCompanyUser.Username, new Object[] { username }));
		if (count > 0) {

			return true;
		} else {
			return false;
		}
	}

	/**
	 * 逻辑删除用户 set is_delete=1
	 * 
	 * @param portalCompanyUserId
	 */
	@Override
	public void deleteUser(Long portalCompanyUserId) {
		PortalCompanyUserBean userInfo = portalCompanyUserDao.queryUserInfo(SpringWebUtils.getRequestCompany(),
				SpringWebUtils.getRequestUser());
		Criteria criteria1=Criteria.create(PortalCompanyUser.class)
				.where("portalCompanyUserId", new Object[] { portalCompanyUserId });
		if (userInfo.getCompanyType() != 1) {
			criteria1.and("companyCode", new Object[] { SpringWebUtils.getRequestCompany() });
		}
		PortalCompanyUser user = jdbcDao.querySingleResult(criteria1);	
		if (user != null) {
			if (user.getDefault_user().intValue() == 1) {
				throw new ServiceException("msg.portal.company.user.cannot.deladminuser");// 不能删除管理员用户
			} else {
				Criteria criteria=Criteria.create(PortalCompanyUser.class).set(PortalCompanyUser.isDelete, 1)
				.where(PortalCompanyUser.portalCompanyUserId, new Object[] { portalCompanyUserId });
				if (userInfo.getCompanyType() != 1) {
					criteria.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() });
				}
				
				jdbcDao.update(criteria);

			}
		} else {
			throw new ServiceException("msg.portal.company.user.notfound");
		}

	}
	
	public void deleteUsers(List<Integer> ids){
		ids.forEach(id->{deleteUser(id.longValue());});
	}
	

	/**
	 * 获取企业用户已分配的角色列表 默认附加条件companyCode
	 * 
	 * @param username
	 * @return
	 */
	@Override
	public List<PortalCompanyRole> queryUserHasRoleList(String username, String companyCode) {
		if (StringUtil.isEmpty(companyCode)) {
			companyCode = SpringWebUtils.getRequestCompany();
		}
		return portalCompanyUserDao.queryUserHasRoleList(username, companyCode);
	}

	/**
	 * 获取企业用户未被分配的角色列表 默认附加条件companyCode
	 * 
	 * @param username
	 * @return
	 */
	@Override
	public List<PortalCompanyRole> queryUserNotHasRoleList(String username, String companyCode) {
		if (StringUtil.isEmpty(companyCode)) {
			companyCode = SpringWebUtils.getRequestCompany();
		}
		return portalCompanyUserDao.queryUserNotHasRoleList(username, companyCode);
	}

	/**
	 * 通过企业查找用户 {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-24
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#queryListByCompany()
	 * 
	 */
	public List<PortalCompanyUser> queryListByCompany(String companyCode) {
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.where(PortalCompanyUser.companyCode, new Object[] { companyCode }).exclude(PortalCompanyUser.Pwd);
		return jdbcDao.queryList(criteria);
	}

	/**
	 * 保存企业用户和角色关系
	 * 
	 * @param username
	 * @param portalCompanyRoleIds
	 */
	@Override
	public void saveUserRole(String username, Long[] portalCompanyRoleIds, String companyCode) {
		if (StringUtil.isEmpty(companyCode)) {
			companyCode = SpringWebUtils.getRequestCompany();
		}
		jdbcDao.delete(Criteria.create(PortalCompanyUserRole.class).where("companyCode", new Object[] { companyCode })
				.and("username", new Object[] { username }));

		for (Long roleId : portalCompanyRoleIds) {
			jdbcDao.insert(Criteria.create(PortalCompanyUserRole.class).set("portalCompanyRoleId", roleId)
					.set("companyCode", companyCode).set("username", username).set("createTime", new Date())
					.set("createUser", SpringWebUtils.getRequestUser()).set("lastUpdateTime", new Date())
					.set("lastUpdateUser", SpringWebUtils.getRequestUser()));

		}
		// 删除该用户redis对应的缓存
		objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY + companyCode + username);
		objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY + companyCode + username);
	}
	
	
	
	@Override
	public void saveUserByRole(List<String> usernames, Long portalCompanyRoleId, String companyCode) {
		if (StringUtil.isEmpty(companyCode)) {
			companyCode = SpringWebUtils.getRequestCompany();
		}
		if(usernames!=null && usernames.size()>0){
			jdbcDao.delete(Criteria.create(PortalCompanyUserRole.class).where("companyCode", new Object[] { companyCode })
					.and("portalCompanyRoleId", new Object[]{portalCompanyRoleId}));
			for(String username : usernames){
				jdbcDao.insert(Criteria.create(PortalCompanyUserRole.class).set("portalCompanyRoleId", portalCompanyRoleId)
						.set("companyCode", companyCode).set("username", username).set("createTime", new Date())
						.set("createUser", SpringWebUtils.getRequestUser()).set("lastUpdateTime", new Date())
						.set("lastUpdateUser", SpringWebUtils.getRequestUser()));
				objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY + companyCode + username);
				objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY + companyCode + username);
			}
		}else {
			jdbcDao.delete(Criteria.create(PortalCompanyUserRole.class).where("companyCode", new Object[] { companyCode })
					.and("portalCompanyRoleId", new Object[]{portalCompanyRoleId}));
		}

		
	}
	
	    
	@Override
	public void removeUserByRole(List<String> usernames, Long portalCompanyRoleId, String companyCode) {
		if (StringUtil.isEmpty(companyCode)) {
			companyCode = SpringWebUtils.getRequestCompany();
		}
		for(String username : usernames){
			jdbcDao.delete(Criteria.create(PortalCompanyUserRole.class).where("companyCode", new Object[] { companyCode })
					.and("username", new Object[] { username }).and("portalCompanyRoleId", new Object[]{portalCompanyRoleId}));
			objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY + companyCode + username);
			objectRedisTemplate.delete(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY + companyCode + username);
		}
	}
	

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-24
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#getCompanyCode()
	 **/
	@Override
	public String getCompanyCode() {
		return SpringWebUtils.getRequestCompany();
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-24
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#getUserId()
	 **/
	@Override
	public Long getUserId() {
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.where(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() })
				.and(PortalCompanyUser.Username, new Object[] { SpringWebUtils.getRequestUser() });
		List<PortalCompanyUser> list = jdbcDao.queryList(criteria);
		return list.get(0).getPortal_company_user_id();
	}

	@Override
	public List<PortalCompanyUser> findUserByCompanyCode(String companyCode) {
		/* return portalCompanyUserDao.findUserByCompanyCode(companyCode); */
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.where(PortalCompanyUser.companyCode, new Object[] { companyCode })
				.and(PortalCompanyUser.isDelete, new Object[] { 0 });
		return jdbcDao.queryList(criteria);
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-30
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#changePassword(java.lang.String,
	 *      java.lang.String)
	 **/
	@Override
	public void changePassword(String username, String password) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		PortalCompanyUserBean userInfo = portalCompanyUserDao.queryUserInfo(SpringWebUtils.getRequestCompany(),
				SpringWebUtils.getRequestUser());
		Criteria criteria = Criteria.create(PortalCompanyUser.class)
				.set(PortalCompanyUser.Pwd, passwordEncoder.encode(password))
				.where(PortalCompanyUser.Username, new Object[] { username });
		if (userInfo.getCompanyType() != 1) {
			criteria.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() });
		}
		jdbcDao.update(criteria);
		//log.dbLog(Level.INFO, "username:"+username+",password:******", "修改了:"+username+"用户的登录密码。");
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-7-5
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#changeMyPassword(java.lang.String)
	 **/
	@Override
	public void changeMyPassword(String password) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		jdbcDao.update(
				Criteria.create(PortalCompanyUser.class).set(PortalCompanyUser.Pwd, passwordEncoder.encode(password))
						.where(PortalCompanyUser.Username, new Object[] { SpringWebUtils.getRequestUser() })
						.and(PortalCompanyUser.companyCode, new Object[] { SpringWebUtils.getRequestCompany() }));
	}

	/**
	 * 查询当前企业用户对应职位部门列表 {@inheritDoc} overridden:
	 * 
	 * @Date : 2016年11月23日
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#getListUserByCompanyCode()
	 *
	 */
	@Override
	public PortalCompanyUserQueryBean getListUserByCompanyUser(PortalCompanyUserQueryBean querybean) {

		querybean.setCompanyCode(SpringWebUtils.getRequestCompany());
		querybean.setResultList(portalCompanyUserDao.getListUserByCompanyUserList(querybean));
		querybean.setTotalRows(portalCompanyUserDao.getListUserByCompanyUserCount(querybean));
		return querybean;
	}

	/**
	 * 
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016年12月9日
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyUserService#getListUserTopOrgByCompanyUser(org.eae.eldf.portal.bean.company.PortalCompanyUserQueryBean)
	 *
	 */
	@Override
	public PortalCompanyUserQueryBean getListUserTopOrgByCompanyUser(PortalCompanyUserQueryBean queryBean) {

		Long orgid = portalCompanyUserDao.getUserTopOrg(
				portalCompanyOrgDao.getCurrentUserOrg(SpringWebUtils.getRequestUser()).getPortal_company_org_id(),
				SpringWebUtils.getRequestCompany());
		queryBean.setCompanyCode(SpringWebUtils.getRequestCompany());
		queryBean.setPortalCompanyOrgId(orgid.toString());
		PageHelper.startPage(queryBean.getStart(), queryBean.getLength());
		queryBean.setResultList(portalCompanyUserDao.getListUserTopOrgByCompanyUserList(queryBean));
		queryBean.setTotalRows(portalCompanyUserDao.getListUserTopOrgByCompanyUserCount(queryBean));
		return queryBean;
	}

	@Override
	public void saveUserOneRole(String username, Integer portalCompanyRoleId) {
		jdbcDao.insert(Criteria.create(PortalCompanyUserRole.class).set("portalCompanyRoleId", portalCompanyRoleId)
				.set("companyCode", SpringWebUtils.getRequestCompany()).set("username", username)
				.set("createTime", new Date()).set("createUser", SpringWebUtils.getRequestUser())
				.set("lastUpdateTime", new Date()).set("lastUpdateUser", SpringWebUtils.getRequestUser()));

	}

	@Override
	public void removeUserOneRole(String username, Integer portalCompanyRoleId) {
		jdbcDao.delete(Criteria.create(PortalCompanyUserRole.class)
				.where("companyCode", new Object[] { SpringWebUtils.getRequestCompany() })
				.and("username", new Object[] { username })
				.and("portalCompanyRoleId", new Object[] { portalCompanyRoleId }));

	}

	@Override
	public void deleteUserBycompanyCodeAndUser(String username, String company_code) {
		jdbcDao.delete(Criteria.create(PortalCompanyUser.class)
				.where("companyCode", new Object[] { SpringWebUtils.getRequestCompany() })
				.and("username", new Object[] { username }));

	}

	@Override
	public PortalCompanyUser userLogin(String companyCode, String username, String pwd) throws ServiceException {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		PortalCompanyUser user = portalCompanyUserDao.userLogin(companyCode, username, pwd);

		if (user == null) {
			throw new ServiceException(SecurityConstant.ERROR_CODE.USER_NOT_FOUND);// 用户不存在
		}
		if (user.getState().intValue() == 0) {
			throw new ServiceException(SecurityConstant.ERROR_CODE.USER_DISABLED);// 用户被禁用
		}
		if(StringUtil.isNotBlank(pwd)){
			if (!passwordEncoder.matches(pwd, user.getPwd())) {
				throw new ServiceException(SecurityConstant.ERROR_CODE.PWD_ERROR);// 密码不正确
			}
		}

		return user;
	}

	@Override
	public PortalCompanyUserBean queryUserInfo(String companyCode, String username) {

		PortalCompanyUserBean user = portalCompanyUserDao.queryUserInfo(companyCode, username);

		return user;
	}

	@Override
	public List<PortalCompanyUserBean> queryUserInfoBy(List<Integer> ids, Integer queryType) {
		List<PortalCompanyUserBean> userList = null;
		switch (queryType) {
		case 0:
			userList=portalCompanyUserDao.queryUserInfoByRole(SpringWebUtils.getRequestCompany(), ids);
			break;
		case 1:
			userList=portalCompanyUserDao.queryUserInfoByLevel(SpringWebUtils.getRequestCompany(), ids);
			break;
		case 2:
			userList=portalCompanyUserDao.queryUserInfoByOrg(SpringWebUtils.getRequestCompany(), ids);
			break;
		case 3:
			userList=portalCompanyUserDao.queryUserInfoByPosition(SpringWebUtils.getRequestCompany(), ids);
			break;
		case 4:
			userList=portalCompanyUserDao.queryUserInfoByIds(SpringWebUtils.getRequestCompany(), ids);
			break;
		default:
			break;
		}
		return userList;
	}

	@Override
	public List<PortalCompanyUserBean> queryUserInfoByConditions(PortalCompanyUserQueryBean queryBean) {
		queryBean.setCompanyCode(SpringWebUtils.getRequestCompany());
		return portalCompanyUserDao.queryUserInfoByConditions(queryBean);
	}

	@Override
	public PortalCompanyUser queryUserDetail(Integer portalCompanyUserId) {
		
		return portalCompanyUserDao.queryUserDetail(portalCompanyUserId);
	}

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param companyCode
	    * @param username
	    * @param pwd
	    * @return
	    * @see com.efast.cafe.portal.remote.company.PortalCompanyUserService#userDoLogin(java.lang.String, java.lang.String, java.lang.String)
	    */
	    
	@Override
	public PortalCompanyUser userDoLogin(String companyCode, String username, String pwd) {
		return userLogin(companyCode,username,pwd);
	}

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @return
	    * @see com.efast.cafe.portal.remote.company.PortalCompanyUserService#queryUserAndOrgInfo()
	    */
	    
	@Override
	public PortalCompanyUserOrgBean queryUserAndOrgInfo() {
		return portalCompanyUserDao.queryUserAndOrgInfo(SpringWebUtils.getRequestCompany(), SpringWebUtils.getRequestUser());
	}

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param companyCode
	    * @param username
	    * @return
	    * @see com.efast.cafe.portal.remote.company.PortalCompanyUserService#api_queryUserInfo(java.lang.String, java.lang.String)
	    */
	    
	@Override
	public PortalCompanyUserBean api_queryUserInfo(String companyCode, String username) {
		return queryUserInfo(companyCode,username);
	}

	@Override
	public List<PortalCompanyRole> api_queryUserHasRoleList(String username, String companyCode) {
		return queryUserHasRoleList(username,companyCode);
	}

	@Override
	public List<PortalCompanyUser> api_queryAllUserInfo(String companyCode) {
		Criteria userCriteria = Criteria.create(PortalCompanyUser.class).where("companyCode",
				new Object[] { SpringWebUtils.getRequestCompany() });
		List<PortalCompanyUser> listUser = jdbcDao.queryList(userCriteria);
		return listUser;
	}

	@Override
	public PortalCompanyUser api_userLogin(String companyCode, String username, String pwd){
		return userLogin(companyCode,username,pwd);
	}

	@Override
	public void doWechatUserCheckAndReg(String companyCode,String openId, String nickName, Integer sex, String headimgurl) {
		Integer count = portalCompanyUserDao.queryUserCountByType(companyCode,openId,"3");
		if(count==0){
			portalCompanyUserDao.regWechatUser(companyCode, openId, "3", nickName, sex);
		}
	}

}
